<template>
  <div class="login-page">
    <div class="login-container">
      <h1 class="title">SpringBoot 后台管理系统</h1>
      <div class="form-toggle">
        <el-button
          :type="isLogin ? 'primary' : 'default'"
          @click="isLogin = true"
          >登录</el-button
        >
        <el-button
          :type="!isLogin ? 'primary' : 'default'"
          @click="isLogin = false"
          >注册</el-button
        >
      </div>

      <!-- 登录表单 -->
      <!-- 监听原生键盘回车事件需要加native，也就是监听组件内部渲染的那个input原生dom元素 -->
      <el-form
        v-if="isLogin"
        ref="loginForm"
        :model="loginForm"
        :rules="rules"
        label-width="80px"
        class="login-form"
        @keyup.enter.native="login"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            v-model="loginForm.password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="captcha">
          <el-row :gutter="10" style="display: flex">
            <el-col :span="12">
              <el-input
                v-model="loginForm.captcha"
                placeholder="请输入验证码"
              ></el-input>
            </el-col>
            <el-col :span="12">
              <img
                :src="captchaUrl"
                @click="refreshCaptcha"
                class="captcha-img"
              />
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="login" :loading="loginLoading"
            >登录</el-button
          >
        </el-form-item>
      </el-form>

      <!-- 注册表单 -->
      <el-form
        v-else
        ref="registerForm"
        :model="registerForm"
        :rules="registerRules"
        label-width="80px"
        class="login-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="registerForm.username"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            v-model="registerForm.password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            type="password"
            v-model="registerForm.confirmPassword"
            placeholder="请再次输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="registerForm.email"
            placeholder="请输入邮箱"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="registerForm.role" placeholder="请选择">
            <el-option label="学生" value="ROLE_STUDENT"></el-option>
            <el-option label="教师" value="ROLE_TEACHER"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="register" :loading="registerLoading"
            >注册</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { login, getRandomImage } from "@/api/sys/login";
import { addUser } from "@/api/sys/user";

export default {
  name: "Login",
  data() {
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.registerForm.password) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    };

    return {
      isLogin: true,
      loginForm: { username: "", password: "", captcha: "" },
      registerForm: {
        username: "",
        password: "",
        confirmPassword: "",
        email: "",
        role: "",
      },
      loginLoading: false,
      registerLoading: false,
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        captcha: [{ required: true, message: "请输入验证码", trigger: "blur" }],
      },
      registerRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 15,
            message: "用户名长度在 3 到 15 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, message: "密码长度至少为 6 个字符", trigger: "blur" },
        ],
        confirmPassword: [
          { required: true, message: "请确认密码", trigger: "blur" },
          { validator: validateConfirmPassword, trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { type: "email", message: "请输入正确的邮箱格式", trigger: "blur" },
        ],
      },
      captchaUrl: "",
      verifyCodeKey: "",
    };
  },
  mounted() {
    this.refreshCaptcha();
  },
  methods: {
    async refreshCaptcha() {
      const res = await getRandomImage();
      this.captchaUrl = res.image;
      this.verifyCodeKey = res.key;
    },
    async login() {
      this.$refs.loginForm.validate(async (valid) => {
        if (valid) {
          this.loginLoading = true;
          try {
            const userInfo = {
              username: this.loginForm.username,
              password: this.loginForm.password,
              verifyCode: this.loginForm.captcha,
              verifyCodeKey: this.verifyCodeKey,
            };
            const res = await login(userInfo);
            if (res && res.code == 200) {
              this.$store.dispatch("Login", {
                token: res.data.token,
                userInfo: res.data,
              });
              this.$message.success("登录成功");
              this.$router.push("/");
            } else {
              this.$message.error(res.message);
              this.refreshCaptcha();
            }
          } catch (error) {
            this.$message.error("登录失败,请稍后重试");
            this.refreshCaptcha();
          } finally {
            this.loginLoading = false;
          }
        } else {
          this.$message.error("请填写所有必填项");
        }
      });
    },
    async register() {
      this.$refs.registerForm.validate(async (valid) => {
        if (valid) {
          this.registerLoading = true;
          try {
            const userInfo = {
              username: this.registerForm.username,
              password: this.registerForm.password,
              email: this.registerForm.email,
              role: this.registerForm.role,
            };
            const res = await addUser(userInfo);
            if (res && res.code == 200) {
              this.$message.success("注册成功，请登录");
              this.isLogin = true;
              this.registerForm = {
                username: "",
                password: "",
                confirmPassword: "",
                email: "",
                role: '',
              };
            } else {
              this.$message.error(res.message);
            }
          } catch (error) {
            this.$message.error("注册失败,请稍后重试");
          } finally {
            this.registerLoading = false;
          }
        } else {
          this.$message.error("请填写所有必填项");
        }
      });
    },
  },
};
</script>

<style scoped>
.login-page {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.login-container {
  background: white;
  padding: 40px;
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
  width: 100%;
  max-width: 400px;
  animation: fadeIn 0.5s ease-in-out;
}

.title {
  text-align: center;
  color: #333;
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 30px;
  letter-spacing: 1px;
}

.form-toggle {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-bottom: 20px;
}

.form-toggle .el-button {
  flex: 1;
  border-radius: 20px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.login-form {
  margin-top: 20px;
}

.el-form-item {
  margin-bottom: 24px;
}

.el-input__inner {
  border-radius: 8px;
  border: 1px solid #dcdfe6;
  transition: all 0.3s ease;
}

.el-input__inner:focus {
  border-color: #409eff;
  box-shadow: 0 0 8px rgba(64, 158, 255, 0.2);
}

.el-button--primary {
  width: 100%;
  border-radius: 8px;
  background: linear-gradient(90deg, #409eff 0%, #79bbff 100%);
  border: none;
  font-weight: 500;
  padding: 12px;
  transition: all 0.3s ease;
}

.el-button--primary:hover {
  background: linear-gradient(90deg, #66b1ff 0%, #a0cfff 100%);
  transform: translateY(-2px);
}

.captcha-img {
  cursor: pointer;
  height: 40px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  transition: all 0.3s ease;
}

.captcha-img:hover {
  transform: scale(1.05);
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@media (max-width: 480px) {
  .login-container {
    padding: 20px;
    margin: 20px;
  }

  .title {
    font-size: 20px;
  }
}
</style>